from typing import List

from sqlalchemy.orm import Session

from server.app.cloud_ide.model.ide_stack import IdeStack
from server.app.cloud_ide.schema.ide_stack.request.ide_stack_create_request import IdeStackCreateRequest
from server.app.cloud_ide.schema.ide_stack.request.ide_stack_update_request import IdeStackUpdateRequest
from server.framework.core.logger import logger


class IdeStackService:
    def get_ide_stack_list(self, db: Session, tenant_id: str,
                           name: str, page_size: int, current_page: int):
        query = db.query(IdeStack)
        if name is not None:
            query = query.filter(IdeStack.name.like("%" + name + "%"))
        query = query.filter(IdeStack.tenant_id == tenant_id)
        query = query.order_by(IdeStack.created.desc())
        total = query.count()
        items = query.limit(page_size).offset((current_page - 1) * page_size).all()
        return items, total

    def get_ide_stack_by_id(self, db: Session, id: str):
        entity = db.query(IdeStack).filter(id == IdeStack.id).one()
        return entity

    def create_ide_stack(self, db: Session, user_name: str, user_id: str, data: IdeStackCreateRequest) -> bool:
        try:
            entity = IdeStack(**data.dict())
            entity.create_user_name = user_name
            entity.create_user_id = user_id
            db.add(entity)
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def delete_ide_stack(self, db: Session, ids: list) -> bool:
        try:
            db.query(IdeStack).filter(IdeStack.id.in_(ids)).delete(synchronize_session=False)
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def update_ide_stack(self, db: Session, data: IdeStackUpdateRequest):
        try:
            db.query(IdeStack).filter(IdeStack.id == data.id).update(data.dict())
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def get_all_ide_stack(self, db: Session, group: str) -> List[IdeStack]:
        return db.query(IdeStack).filter(IdeStack.tenant_id == group).all()
